import { defineStore } from "pinia";
import axios from "axios";
import dayjs from "dayjs";

const useStore = defineStore({
  id: "notam",
  state: () => ({
    content: [],
    count: 0,
    version: "",
    retry: 0,
    retryLimit: 2,
    disabled: false,
  }),
  getters: {
    runwayClosureYesterday() {
      if (this.count == 0) return [];
      return this.filterRunwayClosure(
        dayjs().subtract(1, "day").format("YYYY-MM-DD")
      );
    },
    runwayClosureToday() {
      if (this.count == 0) return [];
      return this.filterRunwayClosure(dayjs().format("YYYY-MM-DD"));
    },
    runwayClosureTomorrow() {
      if (this.count == 0) return [];
      return this.filterRunwayClosure(
        dayjs().add(1, "day").format("YYYY-MM-DD")
      );
    },
  },
  actions: {
    filterRunwayClosure(date = "") {
      let target = date == "" ? dayjs() : dayjs(date);
      let targetString = target.format("YYYY-MM-DD HH:mm:ss");
      let closure = new Array();
      let lastJ = 0;
      for (let i = 0; i < this.count; i++) {
        // munti match in timeSlots
        let thisJ = lastJ;
        if (lastJ > 0) {
          lastJ = 0;
          i--;
        }
        let matched = false;
        let matchedStart = "";
        let matchedEnd = "";
        let notam = this.content[i];
        let airport = notam.airport;
        let text = notam.text;
        let code = notam.number;
        let itemE = notam.origion.ITEME;
        if (!itemE) {
          // 处理没有编组E的情况
          // console.log("缺少编组E的NOTAM: ", notam.number);
        } else if (
          itemE.includes("RWY") &&
          itemE.includes("关") &&
          !itemE.includes("滑") &&
          itemE.indexOf("RWY") < itemE.indexOf("关")
        ) {
          if (notam.timeSlots && notam.timeSlots.length > 0) {
            for (let j = thisJ; j < notam.timeSlots.length; j++) {
              let slot = notam.timeSlots[j];
              let start = slot.start;
              let end = slot.end;
              let slotObjStart = dayjs(start);
              let slotObjEnd = dayjs(end);
              if (
                target.format("YYYYMMDD") == slotObjStart.format("YYYYMMDD") ||
                target.format("YYYYMMDD") == slotObjEnd.format("YYYYMMDD")
              ) {
                if (matched) {
                  lastJ = j;
                  break;
                } else {
                  matched = true;
                  matchedStart = start;
                  matchedEnd = end;
                  // break;
                }
              }
            }
          } else {
            // let effectiveObj = dayjs(notam.effectiveTime);
            // if (target.format("YYYYMMDD") == effectiveObj.format("YYYYMMDD")) {
            if (
              target.isSameOrAfter(notam.effectiveTime, "day") &&
              target.isSameOrBefore(notam.expirationTime, "day")
            ) {
              matched = true;
              matchedStart = notam.effectiveTime;
              matchedEnd = notam.expirationTime;
            }
          }
          if (matched) {
            // console.log(notam.text);
            let start = matchedStart;
            let end = matchedEnd;
            let runways = new Array();
            if (airport == "ZUUU") {
              if (itemE.includes("02L") || itemE.includes("20R")) {
                runways.push("02L/20R");
              } else if (itemE.includes("02R") || itemE.includes("20L")) {
                runways.push("02R/20L");
              }
            } else if (airport == "ZUTF") {
              if (itemE.includes("02") || itemE.includes("20")) {
                runways.push("02/20");
              } else if (itemE.includes("01") || itemE.includes("19")) {
                runways.push("01/19");
              } else if (itemE.includes("11") || itemE.includes("29")) {
                runways.push("11");
              }
            } else if (airport == "ZUMY") {
              if (itemE.includes("14") || itemE.includes("32")) {
                runways.push("14/32");
              }
            } else if (airport == "ZULZ") {
              if (itemE.includes("07") || itemE.includes("25")) {
                runways.push("07/25");
              }
            } else if (airport == "ZUYB") {
              if (itemE.includes("11") || itemE.includes("29")) {
                runways.push("11/29");
              }
            }
            closure.push({ airport, start, end, runways, text, code });
          }
        }
      }
      // closure.sort((a, b) => a.airport.localeCompare(b.airport));
      closure.sort((a, b) =>
        a.airport == "ZUUU"
          ? true
          : a.airport == "ZUTF"
          ? true
          : a.airport == "ZUMY"
          ? true
          : false
      );
      // console.log("RWY Closure: ", targetString, closure);
      return closure;
    },
    load() {
      return new Promise((resolve, reject) => {
        axios
          .get("api/activity_notam_get.php")
          .then((response) => {
            this.disabled = response.data.disabled;
            if (
              (!response.data.count ||
                !response.data.content ||
                response.data.content == undefined ||
                !response.data.version ||
                response.data.content.length == 0 || // count all content
                this.count > response.data.count ||
                response.data.content.filter(
                  (item) => item.airport == "ZUUU"
                ) == 0 || // count ZUUU
                response.data.content.filter(
                  (item) => item.airport == "ZUTF"
                ) == 0) && // count ZUTF
              this.retry < this.retryLimit
            ) {
              console.log(
                "Going to retry to get NOTAM! ",
                "currentCount",
                this.count,
                "responseCount",
                response.data.count,
                dayjs().format("@HH:mm:ss")
              );
              setTimeout(() => {
                console.log(
                  "Retrying...",
                  `${this.retry}/${this.retryLimit}`,
                  dayjs().format("@HH:mm:ss")
                );
                this.retry++;
                this.load()
                  .then((data) => resolve(data))
                  .catch((err) => reject(err));
              }, 1000);
            } else {
              this.content = response.data.content;
              this.count = response.data.count;
              this.version = response.data.version;
              this.retry = 0;
            }
            // console.log(response.data.content);
            resolve(response.data);
          })
          .catch((error) => {
            console.error(error);
            reject(error);
          });
      });
    },
    refresh(force = 0) {
      return new Promise((resolve, reject) => {
        axios
          .get("api/activity_notam_load.php?force=" + force)
          .then((response) => {
            // console.log("loadNOTAM", response.data);
            resolve(response.data);
          })
          .catch((error) => {
            console.error(error);
            reject(error);
          });
      });
    },
  },
});

export default useStore;
